package com.eeGroup.config;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {

        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");

        model.addAttribute("status", statusCode);
        model.addAttribute("error", throwable != null ? throwable.getMessage() : "未知错误");


        if (statusCode != null) {
            switch (statusCode) {
                case 404:
                    return "error/error404"; // 返回 404 页面
                case 500:
                    return "error/error500"; // 返回 500 页面
                default:
                    return "error/error"; // 返回通用错误页面
            }
        }

        return "error/error"; // 默认返回通用错误页面
    }


    public String getErrorPath() {
        return "/error";
    }
}